using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using WalkingTec.Mvvm.Core;

namespace ReaWTM.LayuiHelper
{
	public enum ButtonTargetEnum { Layer, self, newwindow, currentwindow }
	[HtmlTargetElement("wt:linkbutton", Attributes = "url", TagStructure = TagStructure.WithoutEndTag)]
	public class LinkButtonTagHelper : BaseButtonTag
	{
		BaseVM vm = null;
		/// <summary>
		/// 按钮绑定的Vm
		/// 用于判断url是否可访问
		/// 不能访问则隐藏
		/// </summary>
		public bool IsCheckAccess { get; set; }

		public ModelExpression Vm { get; set; }

		/// <summary>
		/// 访问条件
		/// </summary>
		public bool AccessCondition { get; set; } = true;
		/// <summary>
		/// 是否使用<a>的形式输出
		/// </summary>
		public bool IsLink { get; set; }

		/// <summary>
		/// 跳转模式
		/// </summary>
		public ButtonTargetEnum Target { get; set; } = ButtonTargetEnum.Layer;

		/// <summary>
		/// 跳转地址
		/// </summary>
		public string Url { get; set; }

		/// <summary>
		/// 如果跳转模式是Layer，设置弹出窗口标题
		/// </summary>
		public string WindowTitle { get; set; }


		/// <summary>
		/// 请求数据
		/// </summary>
		public Dictionary<string, object> CustomData { get; set; }

		string GetCustomData()
		{
			if (CustomData == null)
			{
				return "undefined";
			}
			else
			{
				return JsonSerializer.Serialize(CustomData, JsonOptions);
			}
		}
		public bool Max { get; set; }

		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			StringBuilder builder = new StringBuilder();
			SetCascadeValue(context, this);

			/// 判断按钮是否可用
			if (IsCheckAccess)
			{
				if (Vm != null)
				{
					vm = Vm.Model as BaseVM;
				}
				else
				{
					UseCascadeParameter<FormTagHelper>(context, x =>
					{
						vm = x.Vm.Model as BaseVM;
					});
				}

				if (vm == null)
				{
					return;
				}

				if (!AccessCondition || !vm.Wtm.IsAccessable(Url))
				{
					return;
				}
			}


			if (IsLink == false)
			{
				output.Attributes.SetAttribute("type", "button");
			}
			else
			{
				output.TagName = "a";
				output.TagMode = TagMode.StartTagAndEndTag;
				output.Attributes.SetAttribute("href", "#");
			}

			if (Url.StartsWith("~"))
			{
				Url = Url.TrimStart('~');
				SetDictValue("is-public", "false");
			}

			builder.Append($@"
<script>
wtm.linkbutton_Render({{
confirmTxt:'{ConfirmTxt}',
data:{GetCustomData()},
divId:'{vm?.ViewDivId}',
id:'{Id}',
title:'{WindowTitle}',
type:'{Target.ToString().ToLower()}',
url:'{Url}',
isPublic:{GetBooleanString(GetDictValue("is-public") == "true")},
}});
</script>
");
			output.PostElement.AppendHtml(builder.ToString());
			base.Process(context, output);
		}

	}
}
